package com.pac.file.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.common.page.Page;
import com.common.page.PageContext;
import com.common.tools.StringTools;
import com.common.tools.TimeTools;
import com.common.util.LogicException;
import com.common.util.PropertyUtils;
import com.pac.file.bean.FileBean;
import com.pac.file.service.FileService;

/**
 * 文件处理
 * 
 * @author chenlujun
 * @version [版本号, 2014-11-7]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@Scope("prototype")
@RequestMapping("/file")
public class FileController {

	private static Logger logger = Logger.getLogger(FileController.class);

	@Autowired
	private FileService fileService;

	/** 上传文件
	 * @param myfiles 文件数据
	 * @param filePath 文件保存的目录结构/folder1/folder2/folder3
	 * @return
	 * @throws IOException
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/upload")
	public ModelAndView upload(@RequestParam MultipartFile[] myfiles,String filePath) throws IOException {

		ModelAndView mov = new ModelAndView();
		mov.setViewName("/file/fileList");
		
		if(StringTools.isNull(filePath))
		{
			filePath=TimeTools.now("yyyy")+"/"+TimeTools.now("MM")+"/"+TimeTools.now("dd");
		}

		for (MultipartFile myfile : myfiles) {

			if (myfile.isEmpty()) {
				logger.info("上传文件，文件未上传");
				break;
			} else {

				try {
					String tempDir = PropertyUtils.getValue("file.temp.dir");
					tempDir += "/" + StringTools.randomCode(32) + ".tmp";
					File upFile = new File(tempDir);
					myfile.transferTo(upFile);

					fileService.uploadFile(upFile,
							myfile.getOriginalFilename(), filePath);
					// 删除临时文件
					upFile.delete();
				} catch (Exception e) {
					logger.error("上传文件出错，" + e.getMessage());
				}
			}
		}

		return mov;
	}

	/**
	 * 进入文件列表
	 * 
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/list")
	public ModelAndView toFileListPage() {
		ModelAndView mov = new ModelAndView();
		mov.setViewName("/file/fileList");

		return mov;
	}

	/**
	 * 文件列表
	 * 
	 * @param fileBean
	 * @param page
	 * @param rows
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Page queryFileList(FileBean fileBean, int page, int rows) {
		// 设置每页记录数
		PageContext.getContext().setPageSize(rows);
		// 跳转到指定页
		PageContext.getContext().gotoPage(page);

		List<FileBean> fileBeanList = fileService.queryFile(fileBean);

		Page currentPage = new Page();
		// 总行数
		int totlaRols = PageContext.getContext().getTotal();
		currentPage.setTotal(totlaRols);
		currentPage.setRows(fileBeanList);

		return currentPage;
	}

	/** 下载文件
	 * @param fileName 文件名
	 * @param filePath 文件URL
	 * @return
	 * @throws IOException
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("download")
	public ResponseEntity<byte[]> download(String fileName, String filePath)
			throws IOException {
		
		if(StringTools.isNull(filePath))
		{
			return null;
		}
		
		if(filePath.indexOf('.')<0)
		{
			return null;
		}
		
		if(StringTools.isNull(fileName))
		{
			//文件名为空，随机生成一个文件名
			fileName=StringTools.randomCode(20)+filePath.substring(filePath.lastIndexOf('.')+1);
		}
		
		//从远端服务器获取文件流
		HttpClient httpClient=new HttpClient();
		GetMethod getMethod = new GetMethod(filePath);
		 // 由于要上传的文件可能比较大,因此在此设置最大的连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		httpClient.executeMethod(getMethod);
		
		HttpHeaders headers = new HttpHeaders();
		// 为了解决中文名称乱码问题
		fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(getMethod.getResponseBody(),
				headers, HttpStatus.CREATED);
	}

	/** 删除文件
	 * @param fileBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delFile(FileBean fileBean)
	{
		boolean result = true;
		String msg = "";
		
		try {
			fileService.delFile(fileBean);
			msg = "删除文件["+fileBean.getName()+"]成功";
		} catch (LogicException e) {
			result = false;
			msg = "删除文件失败，"+e.getMessage();
			logger.error("删除文件出错，"+e.getMessage());
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);
		
		return map;
	}
	
}
